<template>
  <canvas :id="cId" width="1304" height="749"></canvas>
</template>

<script>
export default {
  name: "canvasMove.vue",
  props:['cId','movePos'],
  mounted() {
    this.handleExecute(this.movePos[0],this.movePos[1])
  },
  methods:{
    handleExecute(x, y) {
      // 获取canvas元素
      const canvas = document.querySelector('#'+this.cId)
      if(!canvas) return
      // 获取canvas渲染上下文
      const ctx = canvas.getContext('2d')
      // 定义起点和终点的坐标
      const startX = 820
      const startY = 650
      let endX = x
      let endY = y
      let nextX
      let nextY
      // 第一帧执行的时间
      let startTime;
      // 期望动画持续的时间
      const duration = 3000

      // 创建路径
      ctx.beginPath()
      ctx.moveTo(startX, startY)
      // 设置线条样式
      ctx.strokeStyle = `rgba(${238}, ${161}, ${47},${0.25})`
      ctx.lineWidth = 5
      const step = (currentTime) => {

        !startTime && (startTime = currentTime)
        // 已经过去的时间(ms)
        const timeElapsed = currentTime - startTime
        // 动画执行的进度 {0,1}
        const progress = Math.min(timeElapsed / duration, 1)
        // 绘制方法
        const draw = () => {
          nextX = startX + (endX - startX) * progress
          nextY = startY + (endY - startY) * progress
          ctx.lineTo(nextX, nextY)
          ctx.stroke()
        }
        draw()
        if (progress < 1) {
          requestAnimationFrame(step)
        } else {
          ctx.clearRect(0, 0, 1304, 749);
          setTimeout(_=>{
            this.handleExecute(x, y)
          },3100)

        }
      }
      requestAnimationFrame(step)
    },
  }

}
</script>

<style>
canvas{
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1;
}
</style>